﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Security.Principal;
using System.Xml.Linq;
using COM.Data;

namespace COM.Service
{
    /// <summary>
    /// 实现最常用的角色/功能项绑定
    /// 及用户对功能项操作鉴权,
    /// 未实现对扩展鉴权参数的验证
    /// </summary>
    public class PermissionService : IPermissionItemService,IPermissionService
    {
        private IPrincipalService principalService;
        private IRolePermissionDataService rolePermissionDataService;
        public PermissionService(IRolePermissionDataService rolePermissionDataService,IPrincipalService principalService, IPermissionRoleListService permissionRoleListService)
        {
            this.principalService = principalService;
            this.rolePermissionDataService = rolePermissionDataService;
        }

        public virtual bool TryTestAllowPermissionItem(string enumPermissionName)
        {
            foreach (var item in this.CurrentUser.RoleNameList)
            {
                if (this.rolePermissionDataService.HasPermission(item, enumPermissionName))
                    return true;
            }

            return false;
        }

        public bool AllowPermissionItem(string enumPermissionName)
        {
            if (!this.TryTestAllowPermissionItem(enumPermissionName))
                throw new PermissionException() { PermissionName = enumPermissionName };
            return true;
        }

        public IPermissionUserPrincipal CurrentUser
        {
            get
            {
                return this.principalService.CurrentUser;
            }
        }

    }

}


